import { reqUserLogin, reqUserLogout } from "@/api"

const state = {
  userInfo: {
    // name: '',
    // token:''
    name: localStorage.getItem('userName'),
    token:localStorage.getItem('token')
  }
}
const actions = {
  // 1. 用户登陆
  async userLogin({commit},userObj) {
    const result = await reqUserLogin(userObj)
    if (result.code === 200) {
      commit('SAVE_USER_INFO', result.data)
      
      localStorage.setItem('token', result.data.token)
      localStorage.setItem('userName', result.data.nickName)
    }
    return result
  },
  // 2. 用户登出
  async userLogout({commit}) {
    const result = await reqUserLogout()
    if (result.code === 200) {
      commit('REMOVE_USER_INFO')
    }
  }
}
const mutations = {
  SAVE_USER_INFO(state,payload) {
    // state.userInfo.name = 
    state.userInfo.name = payload.nickName 
    state.userInfo.token = payload.token
  },
  REMOVE_USER_INFO(state) {
    state.userInfo.name = ''
    state.userInfo.token = ''
    
    localStorage.removeItem('userName')
    localStorage.removeItem('token')
  }
  

  // 存储到vuex中的数据，其实是在内存中来存储的，保要页面一刷新，数据就不存在了，也就相当于vuex初始化了 为了长久存储，我们需要额外存到本地存储中一份
}


export default {
  namespaced:true,
  state,
  actions,
  mutations
}